/*
 * @Author: wangqizhang
 * @Date: 2024-04-29 16:04:18
 * @LastEditors: wangqizhang
 * @LastEditTime: 2024-05-12 16:34:29
 * @FilePath: /suixinji-server/middleWare/index.js
 * @Description:
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */
const jwt = require('jsonwebtoken');
const { getNormalConfig } = require('../config/config');
const VAR_SEQUENCE_KEY = getNormalConfig('VAR_SEQUENCE_KEY');
const validBodyData = async (ctx, next, modelParams) => {
  //判断是否存在请求体
  if (ctx.request.body) {
    for (const key in modelParams) {
      if (modelParams[key].required) {
        if (!ctx.request.body[key]) {
          ctx.status = 400;
          ctx.body = {
            code: '9999',
            message: `${key}不能为空`,
            data: null,
          };
          return;
        }
      }
    }
  } else {
    ctx.status = 400;
    ctx.body = {
      code: '9999',
      message: '请求体不能为空',
      data: null,
    };
    return;
  }
  await next();
};
const validateToken = async (ctx, next) => {
  if (!ctx.request.headers.authorization) {
    ctx.status = 500;
    ctx.body = {
      code: '9999',
      message: '没有提供token',
      data: null,
    };
    return;
  }
  const { authorization } = ctx.request.headers;
  const token = String(authorization.replace('Bearer ', ''));
  // 验证token的合法性
  try {
    const user = jwt.verify(token, VAR_SEQUENCE_KEY);
    ctx.state.user = user;
  } catch (error) {
    ctx.status = 403;
    ctx.body = {
      code: '9999',
      message: 'token错误或过期失效',
      data: null,
    };
    return;
  }
  await next();
};
module.exports = { validBodyData, validateToken };
